<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Tools\ServerAction;
use App\Models\Base\Regional;
use App\Models\Base\ServerList;
use App\Models\Base\ServerPlan;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 开服计划.
 */
class ServerPlanController extends Controller
{
    use ModelForm;
    protected $number;

    /**
     * [index 开服计划列表].
     *
     * @Author   王文凡
     * @DateTime 2018-03-09
     *
     * @version  1.0
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header(trans('game.server_manger'));
            $content->description(trans('game.open_server_plan'));
            $content->body($this->grid()->render());
        });
    }

    /**
     * [grid 列表视图].
     *
     * @Author   王文凡
     * @DateTime 2018-03-09
     *
     * @version  1.0
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = Admin::grid(ServerPlan::class, function (Grid $grid) {
            $grid->model()->orderBy('open_time', 'desc');
            $grid->id('ID')->sortable();
            $grid->server_id(trans('game.server_id'));
            $grid->name(trans('game.server_name'));
            $grid->region()->name(trans('game.region_name'));
            $grid->port(trans('game.port'));
            $grid->desc(trans('game.desc'));
            $grid->open_time(trans('game.foreign_time'));

            $grid->status(trans('game.status'))->display(function ($status) {
                switch ($status) {
                    case '0':
                        return "<span class='label bg-red'>".trans('game.to_perform')."</span>";
                        break;

                    case '1':
                        return "<span class='label bg-green'>".trans('game.to_foreign')."</span>";
                        break;
                    case '2':
                        return "<span class='label bg-blue'>".trans('game.completed')."</span>";
                        break;
                }
            });

            $grid->tools(function ($tools) {
                $button = '<a href="javascript:void(0)" id="serverImport" class="btn btn-sm btn-success pull-right">
                                <i class="fa fa-save"></i>&nbsp;&nbsp;'.trans('game.bulk_import').'
                            </a>';
                $tools->append($button);
                $tools->append(new ServerAction());
            });

            $grid->filter(function ($filter) {
                $filter->disableIdFilter();
                $filter->like('name', trans('game.server_name'));
                $filter->equal('status', trans('game.status'))->select([trans('game.to_perform'), trans('game.to_foreign'), trans('game.completed')]);
            });
        });

        return $grid;
    }

    /**
     * [create 新增开服计划].
     *
     * @Author   王文凡
     * @DateTime 2018-03-09
     *
     * @version  1.0
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header(trans('game.server_manger'));
            $content->description(trans('admin.new'));
            $content->body($this->form());
        });
    }

    /**
     * [form 表单].
     *
     * @Author   王文凡
     * @DateTime 2018-03-08
     *
     * @version  1.0
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(ServerPlan::class, function (Form $form) {
            //当前最新服务器数据
            $one = ServerList::orderBy('server_id', 'desc')->first();
            //设置默认值
            $old_server_id = $one ? $one->server_id + 1 : 1;
            $old_port = $one ? $one->port + 1 : 6601;
            $form->text('server_id', trans('game.server_id'))->default($old_server_id)->rules('required|numeric');
            $form->text('port', trans('game.port'))->default($old_port)->rules('required|numeric');
            $form->text('name', trans('game.server_name'))->default('双线'.$old_server_id.'服')->rules('required');
            $form->select('reg_id', trans('game.region_name'))->options(Regional::all()->pluck('name', 'id'))->rules('required');
            $form->datetime('open_time', trans('game.foreign_time'))->default('');
            $form->text('merge_ids', trans('game.merge_config'))->help(trans('game.merge_help'));
            $form->radio('is_add', trans('game.join_only'))->options(['1' => trans('game.yes'), '0' => trans('game.no')])->default('0')->help(trans('game.no_server_open'));
            $form->text('desc', trans('game.desc'))->rules('required');
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     *
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header(trans('game.server_manger'));
            $content->description(trans('admin.edit'));
            $content->body($this->form()->edit($id));
        });
    }

    /**
     * [import 批量导入开服].
     *
     * @Author   王文凡
     * @DateTime 2018-05-21
     *
     * @version  1.0
     *
     * @param Request $request [description]
     *
     * @return string
     */
    public function import(Request $request)
    {
        if (null == $request->file('excel_file')) {
            return back()->with(admin_toastr(trans('game.update_file'), 'error'))->withInput();
        }
        $filePath = $request->file('excel_file')->getRealPath();
        $self = $this;
        Excel::load($filePath, function ($reader) use ($self) {
            $data = $reader->get()->toArray();
            if (empty($data[0])) {
                return back()->with(admin_toastr(trans('game.file_error'), 'error'))->withInput();
            }
            $self->number = 0;
            foreach ($data[0] as $key => $value) {
                if (null == $value['server_id']) {
                    continue;
                }
                $attr = [
                    'server_id' => intval($value['server_id']),
                    'name' => $value['server_name'],
                    'status' => 0,
                    'port' => $value['port'],
                    'reg_id' => $value['reg_id'],
                    'open_time' => ($value['open_time'])->toDateTimeString(),
                    'desc' => $value['desc'],
                ];

                $data = ServerPlan::create($attr);
                if ($data) {
                    ++$self->number;
                }
            }
        });
        back()->with(admin_toastr('成功导入'.$this->number.'条'));

        return redirect(route('openServerPlane.index'));
    }
}
